package service

import (
	"product-service/common"
	"product-service/dao"
	"product-service/dao/entity"
)

var (
	PmsBrandService = &pmsBrandService{}
)

type pmsBrandService struct {
}

func (t *pmsBrandService) DeleteById(id int64) *common.CommonReponse {
	_, err := dao.PmsBrandDao.FindById(dao.DB, id)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	err = dao.PmsBrandDao.DeleteById(dao.DB, id)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	return common.OK.WithData(nil)
}

func (t *pmsBrandService) UpdateById(id int64, model *entity.PmsBrand) *common.CommonReponse {
	_, err := dao.PmsBrandDao.FindById(dao.DB, id)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	//开启事务
	begin := dao.DB.Begin()
	err = dao.PmsBrandDao.UpdateById(begin, id, model)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	//更新中间表
	err = dao.PmsCategoryBrandRelationDao.UpdateBrand(begin, id, model.Name)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	begin.Commit()
	return common.OK
}

func (t *pmsBrandService) Save(model *entity.PmsBrand) *common.CommonReponse {
	data, err := dao.PmsBrandDao.Save(dao.DB, model)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	return common.OK.WithData(data)
}

func (t *pmsBrandService) FindById(id int64) *common.CommonReponse {
	data, err := dao.PmsBrandDao.FindById(dao.DB, id)
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	return common.OK.WithData(data)
}

func (t *pmsBrandService) FindAll(pageQuery *common.PageQuery) *common.CommonReponse {
	all, i, err := dao.PmsBrandDao.FindAll(dao.DB, pageQuery)
	page := &common.Page{
		Total: i,
		Data:  all,
	}
	if err != nil {
		return common.Error.WithMsg(err.Error())
	}
	return common.OK.WithData(page)
}
